<?php

namespace App\Http\Controllers;

use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Illuminate\Foundation\Validation\ValidatesRequests;
use Illuminate\Routing\Controller as BaseController;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Log;
use App\Models\Ip;
use App\Models\VisitLog;
use App\Models\Device;
use Minishlink\WebPush\WebPush;
use Minishlink\WebPush\Subscription;


class IndexController extends BaseController
{
    private $tourl = "https://ddd.game/?ch=77nzl&kwaiId=522885443823337487";
    private $kk7 = "https://kk7.org/?ch=2o7io&ttPixelId=CHRCRBBC77U4209V09RG";

    public function index(Request $request)
    {
        $id = $request->get("id");
        $query_string = $request->getQueryString();
        $ip = $this->getClientIp();
        Log::info($ip);
        $long = ip2long($ip);
        Log::info($query_string);

        Ip::create([
            'package_id' => $id ?? '',
            'ip' => $ip,
            'ip_long' => $long,
            'quert_string' => $query_string ?? ""
        ]);

        $name = "Fortune Tiger";
        $two_name = "Fortune Tiger";
        $code = "4,9";
        $is_load = true;
        $is_check = true;
        return view('index', compact('name', 'code', 'is_load', 'is_check', 'two_name'));

    }


    public function api(Request $request)
    {
        $id = $request->get("id");
        $ip = $this->getClientIp();
        Log::info("api:{$ip}");
        $long = ip2long($ip);
        Log::info("api:{$long}");
        $m = Ip::where(['ip' => $ip])->orderBy("id", 'desc')->first();
        if ($m) {
            $url = $this->tourl . "&{$m->quert_string}";
        } else {
            $url = $this->tourl;
        }
        header('Location: ' . $url);
        exit;
    }


    #kk7
    public function kk71(Request $request)
    {
        $id = $request->get("id");
        $query_string = $request->getQueryString();
        $ip = $this->getClientIp();
        Log::info($ip);
        $long = ip2long($ip);
        Log::info($query_string);

        Ip::create([
            'package_id' => $id ?? '',
            'ip' => $ip,
            'ip_long' => $long,
            'quert_string' => $query_string ?? "",
            'type' => 1,
        ]);

        return view('kk7_1_en');
    }

    #pwa b面地址
    public function kk71_api(Request $request)
    {
        $id = $request->get("id");
        $ip = $this->getClientIp();
        Log::info("api:{$ip}");
        $long = ip2long($ip);
        Log::info("api:{$long}");
        $m = Ip::where(['ip' => $ip, 'type' => 1])->orderBy("id", 'desc')->first();
        $this->in_visit(5, $ip);#打点
        if ($m) {
            $url = $this->kk7 . "&{$m->quert_string}";
        } else {
            $url = $this->kk7;
        }
        header('Location: ' . $url);
        exit;
    }

    #安卓b面地址
    public function kk71_android_api(Request $request)
    {
        $id = $request->get("id");
        $ip = $this->getClientIp();
        Log::info("api:{$ip}");
        $long = ip2long($ip);
        Log::info("api:{$long}");
        $m = Ip::where(['ip' => $ip, 'type' => 1])->orderBy("id", 'desc')->first();
        $this->in_visit(6, $ip);#打点
        if ($m) {
            $url = $this->kk7 . "&{$m->quert_string}";
        } else {
            $url = $this->kk7;
        }
        header('Location: ' . $url);
        exit;
    }


    #打点记录
    function visit(Request $request)
    {
        $type = $request->get("type", 0);
        $uuid = $request->get("uuid", '');
        $ip = $this->getClientIp();

        $publicKey = '';
        if($type == 1){
            $publicKey = $this->get_pubkey($uuid);
        }
        $this->in_visit($type, $ip);

        return response()->json(['code' => '200', 'msg' => 'ok','publicKey'=>$publicKey]);
    }


    private function in_visit($type, $ip)
    {
        $long = ip2long($ip);

        if (!in_array($type, [1, 2, 3, 4, 5, 6])) {
            return response()->json(['code' => '200', 'msg' => 'ok']);
            exit;
        }

        VisitLog::create([
            'ip' => $ip,
            'ip_long' => $long,
            'type' => $type,
            'year' => date('Y'),
            'month' => date('m'),
            'day' => date('d'),
            'timestamp' => time(),
            'datetime' => date('Y-m-d H:i:s', time()),
        ]);

    }

    private function get_pubkey($uuid)
    {
        $dedata = Device::query()->where('uuid', $uuid)->first();
        if($dedata){
            return $dedata['publicKey'];
        }else{
            $key_data = create_pwa_secret_key();
            Device::query()->insert([
                'publicKey'=>$key_data['publicKey'],
                'privateKey'=>$key_data['privateKey'],
                'uuid'=>$uuid,
                'created_at'=>date('Y-m-d H:i:s', time()),
            ]);
            return $key_data['publicKey'];
        }
    }

    #保存订阅消息 subscription
    public function subscription(Request $request)
    {
        $podata = $request->post();
        $dedata = Device::query()->where('uuid', $podata['uuid'])->first();
        if($dedata){
            Device::query()->where('uuid', $podata['uuid'])->update(['subscription_data'=>json_encode($podata['pushSubscription'])]);
            return response()->json(['code' => '200', 'msg' => 'ok']);
        }else{
            return response()->json(['code' => '200', 'msg' => '成功']);
        }

//        var_dump($podata);
    }


    public function send_msg()
    {
        $uuid = '64ce962e24084f6eb52506147c571147';
        $dedata = Device::query()->where('uuid', $uuid)->first();

        $subscription = Subscription::create(json_decode($dedata['subscription_data'],true));

        $auth = array(
            'VAPID' => array(
                'subject' => 'https://www.baidu.com',
                'publicKey' => $dedata['publicKey'],
                'privateKey' => $dedata['privateKey'],
            ),
        );

        $webPush = new WebPush($auth);

        $report = $webPush->sendOneNotification(
            $subscription,
            json_encode(['title' => 'Test Notification',
                'body' => 'Hello, this is a test notification!',
                'icon' => 'kk71/g1vg1715074171803190.jpg', // 替换为你的图标路径
                'badge' => 'kk71/g1vg1715074171803190.jpg', // 替换为你的徽章路径
                'url' => 'https://www.baidu.com' // 替换为通知点击时跳转的URL
            ]),
        );


        $endpoint = $report->getRequest()->getUri()->__toString();

        if ($report->isSuccess()) {
            echo "[v] Message sent successfully for subscription {$endpoint}.";
        } else {
            echo "[x] Message failed to sent for subscription {$endpoint}: {$report->getReason()}";
        }

    }




    private function getClientIp()
    {
        if (getenv("HTTP_CLIENT_IP")) {
            $ip = getenv("HTTP_CLIENT_IP");
        } else if (getenv("HTTP_X_FORWARDED_FOR")) {
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        } else if (getenv("HTTP_X_FORWARDED")) {
            $ip = getenv("HTTP_X_FORWARDED");
        } else if (getenv("HTTP_FORWARDED_FOR")) {
            $ip = getenv("HTTP_FORWARDED_FOR");
        } else if (getenv("HTTP_FORWARDED")) {
            $ip = getenv("HTTP_FORWARDED");
        } else {
            $ip = $_SERVER["REMOTE_ADDR"];
        }
        return $ip;

    }
}
